import java.util.*;

/**
 * LCR 114. 火星词典
 * https://leetcode.cn/problems/Jf1JuT/description/
 */
class Solution {
    Map<Character, Set<Character>> edges;
    Map<Character, Integer> in;
    boolean check;
    public String alienOrder(String[] words) {
        edges = new HashMap<>();
        in = new HashMap<>();
        //初始化工作，加入所有字符，入度值为0
        for(String x : words) {
            char[] ch = x.toCharArray();
            for(int i = 0; i < ch.length; i++) {
                in.put(ch[i], 0);
            }
        }
        //建图
        for(int i = 0; i < words.length; i++) {
            for(int j = i + 1; j < words.length; j++) {
                String s1 = words[i], s2 = words[j];
                add(s1, s2);
                if(check) return "";
            }
        }
        //拓扑排序
        Queue<Character> q = new LinkedList<>();
        //把所有入度为0的字符添加进队列
        for(char x : in.keySet()) {
            if(in.get(x) == 0) q.add(x);
        }
        StringBuffer ret = new StringBuffer();
        while(!q.isEmpty()) {
            char t = q.poll();
            ret.append(t);
            //删除与该点相连的边
            if(!edges.containsKey(t)) continue;
            for(char x : edges.getOrDefault(t, new HashSet<>())) {
                in.put(x, in.get(x) - 1);
                if(in.get(x) == 0) q.add(x);
            }
        }
        //3、判断
        for(char ch : in.keySet()) {
            if(in.get(ch) != 0) return "";
        }
        return ret.toString();
    }

    public void add(String s1, String s2) {
        int n = Math.min(s1.length(), s2.length());
        int i = 0;
        for(; i < n; i++) {
            char c1 = s1.charAt(i), c2 = s2.charAt(i);//c1->c2
            if(c1 != c2) {
                if(!edges.containsKey(c1)) {
                    edges.put(c1, new HashSet<>());
                }
                if(!edges.get(c1).contains(c2)) {
                    edges.get(c1).add(c2);
                    in.put(c2, in.get(c2) +1);
                }
                break;
            }
        }
        //前面字符串长度大于后面字符串长度
        if(i == s2.length() && i < s1.length()) check = true;
    }
}